<template>
  <div class="corp-form">
    <el-row :gutter="24">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-scrollbar height="83vh">
          <!-- 公司客户管理 -->
          <vab-card
            class="fixedName"
            :class="{ collapse: useSettingsStore().collapse }"
          >
            <div class="flex_sb">
              <div class="flex">
                <div class="leve_title">
                  公司客户管理-{{
                    maxFormPulsForm
                      ? statusLabel(maxFormPulsForm.status)
                      : AskStautsTitle
                  }}
                </div>
              </div>
              <div class="flex_end" v-if="askType == 'default'">
                <VabButton
                  type="primary"
                  title="更新"
                  @click="askType = 'update'"
                />
              </div>
              <div class="flex_end" v-else>
                <VabButton update title="暂存" @click="handleSubmit(0)" />
                <el-popconfirm
                  width="220"
                  confirm-button-text="确定"
                  cancel-button-text="返回"
                  title="是否确认修改，如有重要信息更新，烦请确认后再提交。"
                  @confirm="handleSubmit(1)"
                >
                  <template #reference>
                    <VabButton type="primary" title="提交" />
                  </template>
                </el-popconfirm>

                <el-popconfirm
                  width="220"
                  confirm-button-text="确定"
                  cancel-button-text="返回"
                  :title="`${
                    askType == 'update' ? '修改' : '新建'
                  }信息未完成，是否确认取消？`"
                  @confirm="handleClose"
                >
                  <template #reference>
                    <VabButton title="取消" />
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </vab-card>
          <!-- 表单 -->
          <el-form
            v-loading="loading"
            label-width="135px"
            ref="maxFormPulsRef"
            :model="maxFormPuls"
            label-position="right"
          >
            <!-- 基础信息 -->
            <BaseInfo
              class="mar_16"
              id="baseInfoEl"
              ref="baseInfoRef"
              :askType="askType"
              :addressOptions="addressOptions"
            />
            <!-- 发票信息 -->
            <InvoiceInfo
              class="mar_16"
              :askType="askType"
              id="InvoiceInfoEl"
              ref="invoiceInfoRef"
              :addressOptions="addressOptions"
            />
            <!-- 银行信息 -->
            <BankInfo
              class="mar_16"
              id="BankInfoEl"
              ref="bankInfoRef"
              :askType="askType"
              :addressOptions="addressOptions"
            />
            <!-- 收货地址信息 -->
            <AddressInfo
              class="mar_16"
              id="addressInfoEl"
              ref="addressInfoRef"
              :askType="askType"
              :addressOptions="addressOptions"
            />
            <!-- 信用额度 -->
            <!-- <CreditInfo id="creditInfoEl" ref="creditInfoRef" /> -->
          </el-form>
        </el-scrollbar>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
  import { useSettingsStore } from '~/src/store/modules/settings'
  import { IsValueHave } from '~/src/utils/utils'
  import { areaOptions, statusLabel } from './means/means'
  import BaseInfo from './means/BaseInfo.vue'
  import InvoiceInfo from './means/InvoiceInfo.vue'
  import BankInfo from './means/BankInfo.vue'
  import AddressInfo from './means/AddressInfo.vue'
  import {
    customerInfo,
    customerInsert,
    customerUpdate,
  } from '~/src/api/dms/customer'
  import { getBaseList } from '~/src/api/dms/public'
  defineOptions({
    name: 'CorpCustomer',
  })

  /**
   * ref
   */
  const proxy: any = getCurrentInstance()?.proxy
  const menuTreeRef = ref()
  const maxFormPulsRef = ref()
  const baseInfoRef = ref()
  const invoiceInfoRef = ref()
  const bankInfoRef = ref()
  const addressInfoRef = ref()
  const creditInfoRef = ref()

  // 请求类型
  const askType = ref('default') //default, copy, new, update

  // 变量
  const maxFormPulsForm = ref<any>(null) //基础数据
  const storage: any = localStorage.getItem('userInfo')
  const userInfo: any = JSON.parse(storage) //用户信息
  const nodeInfo = ref<any>(userInfo)

  const treeCount = ref(0)
  const loading = ref(false)
  const addressOptions = ref([])
  const countryList = ref<any>([])

  // 基础信息
  let maxFormPuls = ref<any>()

  // 滚动指定位置
  const handleScrollInto = (el: any) => {
    document
      .getElementById(el)
      ?.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }

  // 校验提交信息
  const checkSumit = async () => {
    let baseValidate = false
    let invoiceValidate = false
    let bankValidate = false
    let addressValidate = false

    // 【1】基础信息校验
    baseValidate = await baseInfoRef.value.baseRef.validate((valid: any) => {
      if (valid) return true
      return false
    })

    if (!baseValidate) {
      handleScrollInto('baseInfoEl')
      return
    }

    // 【2】发票信息校验
    const invoiceList: never[] =
      invoiceInfoRef.value.invoiceForm.map((item: any) => {
        const {
          invoice_title,
          tax_register_code,
          invoice_bank_name,
          invoice_bank_account,
          invoice_tel,
          invoice_address,
          socialcre_code,
          is_default_invoice,
        } = item
        return {
          invoice_title,
          tax_register_code,
          invoice_bank_name,
          invoice_bank_account,
          invoice_tel,
          invoice_address,
          socialcre_code,
          is_default_invoice,
        }
      }) || []

    if (invoiceList.length) {
      invoiceValidate = invoiceList.some((item: any) => {
        return (
          !item.invoice_title ||
          !item.tax_register_code ||
          !item.invoice_bank_name ||
          !item.invoice_bank_account ||
          !item.invoice_tel ||
          !item.invoice_address ||
          !item.socialcre_code ||
          !IsValueHave(item.is_default_invoice)
        )
      })

      if (invoiceValidate) {
        proxy.$Message('请正确填写发票信息!', 'warning')
        handleScrollInto('InvoiceInfoEl')
        return
      }
    }
    // 【3】发票信息校验
    const bankList: never[] =
      bankInfoRef.value.bankForm.map((item: any) => {
        const { country, account_name, invoice_bank_account, is_default_bank } =
          item
        return {
          country,
          account_name,
          invoice_bank_account,
          is_default_bank,
        }
      }) || []

    if (bankList.length) {
      bankValidate = bankList.some((item: any) => {
        return (
          !item.country ||
          !item.account_name ||
          !item.invoice_bank_account ||
          !IsValueHave(item.is_default_bank)
        )
      })
      if (bankValidate) {
        proxy.$Message('请正确填写银行信息!', 'warning')
        handleScrollInto('InvoiceInfoEl')
        return
      }
    }

    // 【4】收货地址信息校验
    const addressList: never[] =
      addressInfoRef.value.addressForm.map((item: any) => {
        const {
          shipping_contact,
          shipping_tel,
          shipping_address,
          address,
          is_default_consignee,
          is_default_invoicing,
          is_default_payment,
        } = item
        return {
          shipping_contact,
          shipping_tel,
          shipping_address,
          address,
          is_default_consignee,
          is_default_invoicing,
          is_default_payment,
        }
      }) || []

    if (addressList.length) {
      addressValidate = addressList.some((item: any) => {
        return (
          !item.shipping_contact ||
          !item.shipping_tel ||
          !item.shipping_address ||
          !item.address ||
          !IsValueHave(item.is_default_consignee) ||
          !IsValueHave(item.is_default_invoicing) ||
          !IsValueHave(item.is_default_payment)
        )
      })
      if (addressValidate) {
        proxy.$Message('请正确填写收货地址信息!', 'warning')
        handleScrollInto('addressInfoEl')
        return
      }
    }

    return true
  }
  // 提交
  const handleSubmit = async (type = 1) => {
    const sumitInfo = await checkSumit()

    if (!sumitInfo) return

    const query = {
      ...maxFormPulsForm.value,
      ...baseInfoRef.value.baseForm,
      is_group: 0, //1 主集团 0 子集团
      invoice: invoiceInfoRef.value.invoiceForm,
      bank: bankInfoRef.value.bankForm,
      location: addressInfoRef.value.addressForm.map((item: any) => {
        const { shipping_address } = item
        return {
          ...item,
          shipping_address: shipping_address.toString() || '',
        }
      }),
    }

    if (askType.value == 'copy' || askType.value == 'new') {
      customerInsert({ ...query }).then((data: any) => {
        proxy.$Message(`${type == 0 ? '暂存' : '提交'}成功!`, 'success')
        refreshPage()
      })
    } else {
      const { uid } = nodeInfo.value
      // 判断是否为主集团
      if (userInfo.uid == uid) query.is_group = 1

      customerUpdate({ customer: { ...query }, uid }).then((data: any) => {
        proxy.$Message(`${type == 0 ? '暂存' : '提交'}成功!`, 'success')
        refreshPage()
      })
    }
  }
  // 取消
  const handleClose = async () => {
    askType.value = 'default'
  }

  // 刷新页面
  const refreshPage = () => {
    askType.value = 'default'
    _GetCustomerGroupInfo()
    // 更新树状结构
    menuTreeRef.value._GetTreeList()
  }

  // 获取筛选项
  const _GetScreenData = async () => {
    let resCountry = await getBaseList('account_country')
    countryList.value = resCountry.data.map((item: any) => {
      return {
        value: item.uid,
        label: item.name,
      }
    })
  }

  // 获取基础信息
  const _GetCustomerGroupInfo = async () => {
    const { uid } = nodeInfo.value

    loading.value = true
    try {
      let res = await customerInfo({ uid })

      maxFormPulsForm.value = res.data

      console.log(res.data, 'res.datares.data')

      await baseInfoRef.value.updateData(res.data)
      await invoiceInfoRef.value.updateData(res.data)
      await bankInfoRef.value.updateData(res.data, countryList.value)
      await addressInfoRef.value.updateData(res.data)
      // await creditInfoRef.value.updateData(res.data)

      loading.value = false
    } catch (error) {}
  }
  const _GetAreaOptions = async () => {
    addressOptions.value = await areaOptions()
  }

  /**
   * @实例
   */
  // 状态标题
  const AskStautsTitle = computed(() => {
    if (askType.value == 'copy' || askType.value == 'new') return '-创建中'
    if (askType.value == 'update' || askType.value == 'new') return '-更新中'
    return ''
  })

  // 周期
  onMounted(async () => {
    await _GetScreenData()
    _GetCustomerGroupInfo()
    _GetAreaOptions()
  })
</script>
<style lang="scss" scoped>
  @import './means/means.scss';

  .fixedName {
    position: fixed;
    top: 126px;
    z-index: 1988;
    width: calc(100% - 32px - 227px);
    // 左侧tabs 伸缩
    &.collapse {
      width: calc(100% - 32px - 65px);
    }
  }
  @media screen and (max-width: 992px) {
    .fixedName {
      position: fixed;
      top: 110px;
      z-index: 1988;
      width: calc(100% - 40px);
    }
  }
</style>
